const fs = require('fs');
const path = require('path');
const fileSavedDirectory = path.resolve(__dirname, '../uploads');

function savedFile(file) {
    let accessUrl = '';
    let now = new Date();
    let subDirectory = path.resolve(fileSavedDirectory,  `${now.getFullYear()}${now.getMonth()+1}`);

    if(!fs.existsSync(path.resolve(subDirectory))){
        fs.mkdirSync(subDirectory);
    }

    let result = {
        original:{
            path: `/${now.getFullYear()}${now.getMonth()+1}/`,
            name: file.name,
            url: `/${now.getFullYear()}${now.getMonth()+1}/${file.name}`
        }
    };
    let filePath = path.join(subDirectory, file.name);

    // 从临时目录中读取文件
    let reader = fs.createReadStream(file.path);
    let writer = fs.createWriteStream(filePath);

    reader.pipe(writer);

    return result;
}

module.exports = {
    upload: (ctx) => {
        let uploadedFiles = [];
        let files = ctx.request.body.files || {};

        for (let key in files) {
            let file = files[key];

            uploadedFiles.push(savedFile(file));
        }

        return uploadedFiles;
    }
};